package com.net

import com.net.parser.ObjectParser
import com.net.request.BaseRequestBuilder
import com.net.request.GetRequestBuilder
import com.net.request.PostFileRequestBuilder
import com.net.request.PostFormRequestBuilder
import com.net.request.PostJsonRequestBuilder
import okhttp3.OkHttpClient
import okhttp3.Request

/**
 * @describe:仅仅是为了提供链式结构
 * @Author: lixiaopeng
 * @Date: 2020/6/4
 */
class NetUtils(private val request: Request) {

    companion object {
        fun getHttpClient(): OkHttpClient {
            return NetClient.getHttpClient()
        }

        /**
         * 初始化,如果用户没有初始话，则直接用系统的httpClient
         */
        fun init(netClientConfig: NetClientConfig) {
            NetClient.init(netClientConfig)
        }

        fun get(): BaseRequestBuilder {
            return GetRequestBuilder()
        }

        fun postForm(): BaseRequestBuilder {
            return PostFormRequestBuilder()
        }

        fun postJson(): BaseRequestBuilder {
            return PostJsonRequestBuilder()
        }

        fun postFile(): BaseRequestBuilder {
            return PostFileRequestBuilder()
        }

        fun cancelTag(tag: Any) {
            NetClient.cancelTag(tag)
        }
    }

    /**
     * 异步执行
     */
    fun <T> enqueue(clazz: Class<T>? = null, success: ((t: T?) -> Unit)? = null, fail: ((msg: String) -> Unit)? = null) {
        NetClient.enqueue(request, clazz?.let { ObjectParser(clazz) }, success, fail)
    }

    /**
     * 同步执行
     */
    fun <T> execute(clazz: Class<T>? = null): T? {
        return NetClient.execute(request, clazz?.let { ObjectParser(clazz) })
    }

    fun cancelRequest() {
        NetClient.cancelRequest(request)
    }
}